package xin.yangshuai.zookeeper01.case1;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.List;

public class DistributeClient {

    // 注意：逗号左右不能有空格
    private String connectString = "192.168.145.132:2181,192.168.145.133:2181,192.168.145.134:2181";
    // 2000毫秒
    private int sessionTimeout = 2000;

    private ZooKeeper zkClient;

    public void getConnect() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                // 初始化时，会执行一次
                System.out.println("当前监听的节点：" + watchedEvent.getPath());
                try {
                    // 由于注册一次，监听一次，如果想持续监听，可重新注册
                    // getServerList()方法设置了监听，所以每次调用将重新注册监听
                    getServerList();
                } catch (KeeperException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void getServerList() throws KeeperException, InterruptedException {
        // 参数watch设置为true，表示使用zkClient创建时的Watcher，并监听当前节点的子节点的增删变化
        // 提前创建好 /servers 节点
        List<String> children = zkClient.getChildren("/servers", true);
        System.out.println("服务器在线数量：" + children.size());
        for (String child : children) {
            System.out.println("服务器 " + child + " 在线");
        }
    }
}

